<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="电表编号" prop="dbbh">
        <el-input
          v-model="queryParams.dbbh"
          placeholder="请输入电表编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归属载体" prop="zt">
        <el-select
          v-model="queryParams.zt"
          placeholder="请选择归属载体"
          clearable
          filterable
          style="width: 200px"
          @focus="fetchCarrierList"
        >
          <el-option
            v-for="item in carrierList"
            :key="item.nr"
            :label="item.nr"
            :value="item.nr"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="lc">
        <el-input
          v-model="queryParams.lc"
          placeholder="请输入楼层"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
    </el-row>
    <!-- Tab 栏 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="使用中" name="used"></el-tab-pane>
      <el-tab-pane label="空闲" name="free"></el-tab-pane>
    </el-tabs>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column prop="dbbh" label="电表编号" align="center" />
      <el-table-column prop="tid" label="操作码" align="center" width="120" />
      <el-table-column prop="zt" label="归属载体" align="center" />
      <el-table-column prop="lc" label="楼层" width="80" align="center" />
      <el-table-column prop="location" label="所在位置" align="center" />
      <el-table-column
        prop="fjh"
        label="关联房间"
        align="center"
        v-if="activeTab === 'used'"
      >
        <template #default="scope">
          <span
            :style="scope.row.fjh ? 'color:#409eff;cursor:pointer;' : ''"
            @click="scope.row.fjh && handleUpdateRoom(scope.row)"
          >
            {{ scope.row.fjh }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="qymc"
        label="租户"
        align="center"
        width="350"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span
            :style="scope.row.dbyt === '租用' ? 'color:#409eff;cursor:pointer;' : ''"
            @click="scope.row.dbyt === '租用' && openContactDialog(scope.row, 'invoice')"
          >
            {{ scope.row.qymc }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="lxr" label="联系人" align="center">
        <template #default="scope">
          <span
            style="color: #409eff; cursor: pointer"
            @click="scope.row.dbyt === '租用' && openContactDialog(scope.row, 'contact')"
          >
            {{ scope.row.xm != null ? scope.row.xm : "无" }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        prop="dbyt"
        label="用途"
        align="center"
        v-if="activeTab === 'used'"
      />

      <el-table-column prop="magnification" width="80" label="倍率" align="center" />

      <el-table-column prop="dbzt" label="电表状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.dbzt === '使用'" type="success">使用</el-tag>
          <el-tag v-else-if="scope.row.dbzt === '空闲'" type="warning">空闲</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button
            v-if="activeTab === 'free'"
            link
            type="primary"
            @click="handleEnableAssociation(scope.row)"
          >
            启用关联
          </el-button>
          <el-button
            v-if="activeTab === 'used'"
            link
            type="warning"
            @click="handleWithdraw(scope.row)"
          >
            退用消关
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或编辑电表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="meterRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="归属载体" prop="nr">
          <el-select
            v-model="form.nr"
            placeholder="请选择归属载体"
            @change="handleCarrierChange"
          >
            <el-option
              v-for="item in carrierList"
              :key="item.nra"
              :label="item.nr"
              :value="item.nr"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="lc">
          <el-input
            v-model="form.lc"
            placeholder="请输入楼层"
            type="number"
            @input="fetchZlList"
          />
        </el-form-item>
        <el-form-item label="所在位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入所在位置" />
        </el-form-item>
        <el-form-item label="电表倍率" prop="magnification">
          <el-input
            v-model="form.magnification"
            placeholder="请输入电表倍率"
            type="number"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="电表单价" prop="dbdj">
          <el-input
            v-model="form.dbdj"
            placeholder="请输入电表单价"
            type="number"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="操作地址" prop="tid">
          <el-input v-model="form.tid" placeholder="请输入16进制HEX格式操作地址" />
        </el-form-item>
        <el-form-item label="智联器编号" prop="zlid">
          <el-select
            v-model="form.zlid"
            placeholder="请先选择载体与楼层"
            filterable
            @focus="fetchZlList"
            clearable
          >
            <el-option
              v-for="item in zlList"
              :key="item.zlid"
              :label="item.zlid"
              :value="item.zlid"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 启用关联对话框 -->
    <el-dialog
      :title="'启用关联 - ' + enableForm.dbbh"
      v-model="enableDialogVisible"
      width="600px"
      append-to-body
    >
      <el-form
        ref="enableFormRef"
        :model="enableForm"
        :rules="enableRules"
        label-width="120px"
      >
        <el-form-item label="电表用途" prop="yt">
          <el-select
            v-model="enableForm.yt"
            placeholder="请选择电表用途"
            @change="handlePurposeChange"
          >
            <el-option
              v-for="item in purposeList"
              :key="item.pxbh"
              :label="item.nr"
              :value="item.nr"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租户" prop="qymc">
          <template v-if="enableForm.yt === '自用' || enableForm.yt === '公用'">
            <el-input v-model="enableForm.qymc" placeholder="请输入企业名称/区域名称" />
          </template>
          <template v-else-if="enableForm.yt === '租用'">
            <el-select
              v-model="enableForm.qymc"
              placeholder="请选择企业名称"
              @change="handleEnterpriseChange"
            >
              <el-option
                v-for="item in enterpriseListData"
                :key="item.khbh"
                :label="item.qymc"
                :value="item.qymc"
              />
            </el-select>
          </template>
        </el-form-item>
        <!-- 房源选择仅在非公用时显示 -->
        <el-form-item label="房源选择" prop="fjh" v-if="enableForm.yt !== '公用'">
          <el-select v-model="enableForm.fjh" placeholder="请选择房源" multiple>
            <el-option
              v-for="item in roomListData"
              :key="item.fjh"
              :label="item.fjh"
              :value="item.fjh"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="启用日期" prop="qysj">
          <el-date-picker
            v-model="enableForm.qysj"
            type="date"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择启用日期"
            style="width: 100%"
            @change="handleEnableDateChange"
          />
        </el-form-item>
        <el-form-item label="初始电量" prop="csdl">
          <el-input
            v-model="enableForm.csdl"
            placeholder="请选择启用日期"
            type="number"
            :disabled="true"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelEnableAssociation">取消</el-button>
          <el-button type="primary" @click="submitEnableAssociation">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 关联房间更新对话框 -->
    <el-dialog
      title="关联房间更新"
      v-model="updateRoomDialogVisible"
      width="600px"
      append-to-body
    >
      <el-form label-width="100px">
        <el-form-item label="电表编号">
          <el-input v-model="updateRoomForm.dbbh" disabled />
        </el-form-item>
        <el-form-item label="载体位置">
          <el-input v-model="updateRoomForm.zt" disabled />
        </el-form-item>
        <el-form-item label="现关联房间号">
          <el-input v-model="updateRoomForm.fjh" disabled />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="updateRoomForm.qymc" disabled />
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px; font-weight: bold">可选房间列表：</div>
      <el-table
        :data="roomList"
        @selection-change="handleRoomSelectionChange"
        row-key="fjh"
        ref="roomTableRef"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="zt" label="载体" align="center" />
        <el-table-column prop="fjh" label="房间号" align="center" />
        <el-table-column prop="qymc" label="企业名称" align="center" />
      </el-table>
      <template #footer>
        <el-button @click="updateRoomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdateRoom">确定</el-button>
      </template>
    </el-dialog>

    <!-- 退用取消关联对话框 -->
    <el-dialog
      title="退用取消关联"
      v-model="withdrawDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        :model="withdrawForm"
        :rules="withdrawRules"
        ref="withdrawFormRef"
        label-width="100px"
      >
        <el-form-item label="电表用途">
          <el-input v-model="withdrawForm.dbyt" disabled />
        </el-form-item>
        <el-form-item label="租户">
          <el-input v-model="withdrawForm.qymc" disabled />
        </el-form-item>
        <el-form-item label="房源">
          <el-input v-model="withdrawForm.fjh" disabled />
        </el-form-item>

        <el-form-item label="退用日期" prop="tysj">
          <el-date-picker
            v-model="withdrawForm.tysj"
            type="date"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择退用日期"
            style="width: 100%"
            @change="handleWithdrawDateChange"
          />
        </el-form-item>
        <el-form-item label="最终电量" prop="zzdl">
          <el-input v-model="withdrawForm.zzdl" disabled placeholder="请选择退用日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWithdraw">确定</el-button>
      </template>
    </el-dialog>
    <!-- 关联房间更新对话框 -->
    <el-dialog
      title="关联房间更新"
      v-model="updateRoomDialogVisible"
      width="600px"
      append-to-body
    >
      <el-form label-width="100px">
        <el-form-item label="电表编号">
          <el-input v-model="updateRoomForm.dbid" disabled />
        </el-form-item>
        <el-form-item label="载体位置">
          <el-input v-model="updateRoomForm.zt" disabled />
        </el-form-item>
        <el-form-item label="现关联房间号">
          <el-input v-model="updateRoomForm.fjh" disabled />
        </el-form-item>
        <el-form-item label="企业名称">
          <el-input v-model="updateRoomForm.qymc" disabled />
        </el-form-item>
        <el-form-item label="客户编号">
          <el-input v-model="updateRoomForm.khbh" disabled />
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px; font-weight: bold">可选房间列表：</div>
      <el-table
        :data="roomList"
        @selection-change="handleRoomSelectionChange"
        row-key="fjh"
        ref="roomTableRef"
        border
        :highlight-current-row="true"
        :max-height="300"
      >
        <el-table-column type="selection" width="55" :selectable="() => true" />
        <el-table-column prop="zt" label="载体" align="center" />
        <el-table-column prop="fjh" label="房间号" align="center" />
        <el-table-column prop="qymc" label="企业名称" align="center" />
      </el-table>
      <template #footer>
        <el-button @click="updateRoomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdateRoom">确定</el-button>
      </template>
    </el-dialog>

    <!-- 企业信息弹窗 -->
    <el-dialog
      :title="contactDialogQymc"
      v-model="contactDialogVisible"
      width="900px"
      append-to-body
    >
      <div style="margin-bottom: 10px; font-weight: bold">
        客户编号：{{ contactDialogKhbh }}
      </div>
      <el-button
        type="primary"
        @click="openInvoiceEditDialog"
        style="margin-bottom: 10px"
      >
        补充开票信息
      </el-button>
      <el-button
        type="primary"
        @click="openAddContactDialog"
        style="margin-bottom: 10px; margin-left: 10px"
      >
        添加企业成员
      </el-button>
      <el-tabs v-model="contactTab">
        <el-tab-pane label="开票信息" name="invoice">
          <el-descriptions
            v-if="invoiceInfo"
            :column="2"
            border
            style="margin-bottom: 10px"
          >
            <el-descriptions-item label="用户名称">{{
              invoiceInfo.qymc
            }}</el-descriptions-item>
            <el-descriptions-item label="客户编号">{{
              invoiceInfo.khbh
            }}</el-descriptions-item>
            <el-descriptions-item label="统一信用代码">{{
              invoiceInfo.yyzzh
            }}</el-descriptions-item>
            <el-descriptions-item label="载体项目">{{
              invoiceInfo.zt
            }}</el-descriptions-item>
            <el-descriptions-item label="缴费类型">
              <span v-if="invoiceInfo.jflx == 1">后付费</span>
              <span v-else-if="invoiceInfo.jflx == 2">预付费</span>
              <span v-else>--</span>
            </el-descriptions-item>
            <el-descriptions-item label="应收电费/已充值金额">{{
              invoiceInfo.hkzje
            }}</el-descriptions-item>
            <el-descriptions-item label="已收电费金额">{{
              invoiceInfo.yszje
            }}</el-descriptions-item>
            <el-descriptions-item label="未收电费/预充值剩余金额">{{
              invoiceInfo.wszje
            }}</el-descriptions-item>
            <el-descriptions-item label="发票抬头企业名称">{{
              invoiceInfo.kpqym
            }}</el-descriptions-item>
            <el-descriptions-item label="开票税号">{{
              invoiceInfo.kpsh
            }}</el-descriptions-item>
            <el-descriptions-item label="开票类型">{{
              invoiceInfo.kplx
            }}</el-descriptions-item>
            <el-descriptions-item label="可开票金额">{{
              invoiceInfo.Kkpje
            }}</el-descriptions-item>
            <el-descriptions-item label="已开票金额">{{
              invoiceInfo.ykpje
            }}</el-descriptions-item>
            <el-descriptions-item label="未开票金额">{{
              invoiceInfo.wkpje
            }}</el-descriptions-item>
            <el-descriptions-item label="企业状态">{{
              invoiceInfo.qyzt
            }}</el-descriptions-item>
          </el-descriptions>
          <div v-else style="color: #999; padding: 40px 0; text-align: center">
            暂未补充
          </div>
        </el-tab-pane>
        <el-tab-pane label="企业成员" name="contact">
          <el-table :data="contactList">
            <el-table-column prop="xm" label="姓名" align="center" />
            <el-table-column prop="sj" label="手机号" align="center" />
            <el-table-column prop="wxh" label="微信号" align="center" />
            <el-table-column prop="zw" label="职务" align="center" />
            <el-table-column prop="qx" label="权限" align="center" />
            <el-table-column prop="sfjf" label="缴费人" align="center">
              <template #default="scope">
                <span>{{ scope.row.sfjf === 0 ? "是" : "否" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template #default="scope">
                <el-button link @click="openEditContactDialog(scope.row)"
                  >编辑</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 联系人新增/编辑对话框 -->
    <el-dialog
      :title="contactEditMode ? '编辑联系人' : '新增联系人'"
      v-model="contactEditDialogVisible"
      width="900px"
      append-to-body
    >
      <el-form
        :model="contactForm"
        :rules="contactRules"
        ref="contactFormRef"
        label-width="80px"
      >
        <el-form-item label="租户">
          <el-input v-model="contactForm.qymc" disabled />
        </el-form-item>
        <el-form-item label="客户编号">
          <el-input v-model="contactForm.khbh" disabled />
        </el-form-item>
        <el-form-item label="电表编号">
          <el-input v-model="contactForm.dbbh" disabled />
        </el-form-item>
        <el-form-item label="姓名" prop="xm">
          <el-input v-model="contactForm.xm" />
        </el-form-item>
        <el-form-item label="手机号" prop="sj">
          <el-input v-model="contactForm.sj" />
        </el-form-item>
        <el-form-item label="微信号" prop="wxh">
          <el-input v-model="contactForm.wxh" />
        </el-form-item>
        <el-form-item label="职务" prop="zw">
          <el-input v-model="contactForm.zw" placeholder="请输入职务" />
        </el-form-item>
        <el-form-item label="权限" prop="qx">
          <el-radio-group v-model="contactForm.qx">
            <el-radio :label="6">管理员</el-radio>
            <el-radio :label="2">缴费人员</el-radio>
            <el-radio :label="1">查看</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="缴费人" prop="sfjf">
          <el-radio-group v-model="contactForm.sfjf">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="contactEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitContactForm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 补充开票信息弹窗 -->
    <el-dialog
      title="补充开票信息"
      v-model="invoiceEditDialogVisible"
      width="750px"
      append-to-body
    >
      <el-form
        :model="invoiceForm"
        ref="invoiceFormRef"
        label-position="top"
        label-width="120px"
        :inline="true"
        style="margin-top: 10px;display: flex;justify-content: space-around;align-items: center;"
      >
        <el-form-item label="用户名称" prop="qymc">
          <el-input v-model="invoiceForm.qymc" placeholder="请输入用户名称" disabled />
        </el-form-item>
        <el-form-item label="客户编号" prop="khbh">
          <el-input v-model="invoiceForm.khbh" placeholder="请输入客户编号" disabled />
        </el-form-item>
        <el-form-item label="统一信用代码" prop="yyzzh">
          <el-input v-model="invoiceForm.yyzzh" placeholder="请输入统一信用代码" />
        </el-form-item>
        <el-form-item label="载体项目" prop="zt">
          <el-input v-model="invoiceForm.zt" placeholder="请输入载体项目" />
        </el-form-item>
        <el-form-item label="缴费类型" prop="jflx">
          <el-radio-group v-model="invoiceForm.jflx">
            <el-radio :label="1">后付费</el-radio>
            <el-radio :label="2">预付费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="应收电费/已充值金额" prop="hkzje">
          <el-input
            v-model="invoiceForm.hkzje"
            type="number"
            placeholder="请输入应收电费或已充值金额"
          />
        </el-form-item>
        <el-form-item label="已收电费金额" prop="yszje">
          <el-input
            v-model="invoiceForm.yszje"
            type="number"
            placeholder="请输入已收电费金额"
          />
        </el-form-item>
        <el-form-item label="未收电费/预充值剩余金额" prop="wszje">
          <el-input
            v-model="invoiceForm.wszje"
            type="number"
            placeholder="请输入未收电费或预充值剩余金额"
          />
        </el-form-item>
        <el-form-item label="发票抬头企业名称" prop="kpqym">
          <el-input v-model="invoiceForm.kpqym" placeholder="请输入发票抬头企业名称" />
        </el-form-item>
        <el-form-item label="开票税号" prop="kpsh">
          <el-input v-model="invoiceForm.kpsh" placeholder="请输入开票税号" />
        </el-form-item>
        <el-form-item label="开票类型" prop="kplx">
          <el-input v-model="invoiceForm.kplx" placeholder="请输入开票类型" />
        </el-form-item>
        <el-form-item label="可开票金额" prop="Kkpje">
          <el-input
            v-model="invoiceForm.Kkpje"
            type="number"
            placeholder="请输入可开票金额"
          />
        </el-form-item>
        <el-form-item label="已开票金额" prop="ykpje">
          <el-input
            v-model="invoiceForm.ykpje"
            type="number"
            placeholder="请输入已开票金额"
          />
        </el-form-item>
        <el-form-item label="未开票金额" prop="wkpje">
          <el-input
            v-model="invoiceForm.wkpje"
            type="number"
            placeholder="请输入未开票金额"
          />
        </el-form-item>
        <el-form-item label="企业状态" prop="qyzt">
          <el-input
            v-model="invoiceForm.qyzt"
            placeholder="请输入企业状态，如办结/注销"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="invoiceEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitInvoiceForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, watch } from "vue";
import { parseTime } from "@/utils/ruoyi.js";
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

import {
  useList,
  freeList,
  selectzt,
  addMeter,
  enterpriseList,
  startAssociation,
  selectRoom,
  startDayPower,
  withdraw,
  selectContact,
  addContact,
  updateContact,
  selectAmmeter1,
  selectRoom1,
  updateRoom,
  selectAllZl,
} from "@/api/carrier/ammeter";
import { selectzh, addInvoice } from "@/api/carrier/index";
import { nextTick } from "vue";

const activeTab = ref("used"); // 当前 Tab
const tableData = ref([]);
const loading = ref(true);
const open = ref(false);
const total = ref(0);
const title = ref("");
const carrierList = ref([]); // 载体列表
const purposeList = ref([]); // 电表用途列表
const enableDialogVisible = ref(false); // 启用关联对话框可见性
const enterpriseListData = ref([]); // 企业列表数据
const roomListData = ref([]); // 房源列表数据
const contactDialogVisible = ref(false); // 联系人列表对话框可见性
const contactEditDialogVisible = ref(false); // 联系人编辑对话框可见性
const contactEditMode = ref(false); // 联系人编辑模式
const contactList = ref([]); // 联系人列表
const contactTab = ref("invoice"); // tabs: contact/企业成员, invoice/开票信息
const updateRoomDialogVisible = ref(false); // 关联房间更新对话框可见性
const roomList = ref([]); // 可选房间列表
const selectedRooms = ref([]);
const zlList = ref([]); // 智联器列表
const withdrawDialogVisible = ref(false); // 退用取消关联对话框可见性
const withdrawForm = reactive({
  dbbh: "",
  qymc: "",
  fjh: "",
  dbyt: "",
  tysj: "",
  zzdl: "",
});
let withdrawRow = null;
// 退用取消关联表单校验规则
const withdrawRules = {
  tysj: [{ required: true, message: "请选择退用日期", trigger: "change" }],
  zzdl: [{ required: true, message: "未获取到最终电量", trigger: "blur" }],
};
const withdrawFormRef = ref(); // 表单ref
const data = reactive({
  form: {
    dbbh: undefined,
    nr: undefined,
    nra: undefined,
    lc: undefined,
    location: undefined,
    magnification: undefined,
    dbdj: undefined, // 新增：电表单价
    tid: undefined,
    zlid: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dbbh: undefined,
    zt: undefined,
    lc: undefined,
  },
  rules: {
    nr: [{ required: true, message: "请选择归属载体", trigger: "change" }],
    lc: [{ required: true, message: "请输入楼层", trigger: "blur" }],
    location: [{ required: true, message: "请输入所在位置", trigger: "blur" }],
    magnification: [
      { required: true, message: "请输入电表倍率", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "倍率格式不正确，最多两位小数",
        trigger: "blur",
      },
    ],
    tid: [{ required: true, message: "请输入操作地址", trigger: "blur" }],
    dbdj: [
      { required: true, message: "请输入电表单价", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "单价格式不正确，最多两位小数",
        trigger: "blur",
      },
    ],
    zlid: [{ message: "请选择智联器编号", trigger: "change" }],
  },
});

const { queryParams, rules, form } = toRefs(data);

const enableForm = reactive({
  dbbh: "", // 电表编号
  qymc: "", // 企业名称
  fjh: [], // 房源编号
  yt: "租用", // 电表用途
  qysj: "", // 启用日期
  csdl: 0, // 初始电量
});

const enableRules = {
  qymc: [{ required: true, message: "请选择企业名称", trigger: "change" }],
  fjh: [{ required: true, message: "请选择房源", trigger: "change" }],
  yt: [{ required: true, message: "请选择电表用途", trigger: "change" }],
  qysj: [{ required: true, message: "请选择启用日期", trigger: "change" }],
  csdl: [{ required: true, message: "请选择启用日期", trigger: "blur" }],
};
const enableFormRef = ref(); // 表单ref
// 联系人弹窗相关数据
const contactDialogQymc = ref(""); // 弹窗上方租户
const contactDialogDbbh = ref(""); // 弹窗电表编号
const contactDialogKhbh = ref(""); // 弹窗客户编号

// 联系人表单
const contactForm = reactive({
  qymc: "",
  khbh: "",
  dbbh: "",
  xm: "",
  sj: "",
  wxh: "",
  zw: "",
  qx: "",
  sfjf: 0,
  yhID: undefined, // 编辑时用
});

// 联系人表单校验规则
const contactRules = {
  xm: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  sj: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  zw: [{ required: true, message: "请输入职务", trigger: "blur" }],
  qx: [{ required: true, message: "请选择权限", trigger: "change" }],
  sfjf: [{ required: true, message: "请选择是否为缴费人", trigger: "change" }],
};

// 监听权限变化，权限为1时自动设置为非缴费人
watch(
  () => contactForm.qx,
  (val) => {
    if (val === 1) {
      contactForm.sfjf = 1;
    }
  }
);
const contactFormRef = ref(); // 表单ref
// 打开联系人列表弹窗
function openContactDialog(row, type) {
  contactDialogQymc.value = row.qymc;
  contactDialogDbbh.value = row.dbbh;
  contactDialogKhbh.value = row.khbh;
  contactDialogVisible.value = true;
  // 默认tab

  contactTab.value = type;
  fetchContactList();
  fetchInvoiceInfo();
}

// 获取联系人列表
function fetchContactList() {
  selectContact({
    qymc: contactDialogQymc.value,
    dbbh: contactDialogDbbh.value,
    khbh: contactDialogKhbh.value,
  }).then((res) => {
    contactList.value = res.data || [];
  });
}

// 打开编辑联系人弹窗
function openEditContactDialog(row) {
  contactEditMode.value = true;
  Object.assign(contactForm, {
    qymc: contactDialogQymc.value,
    khbh: contactDialogKhbh.value,
    dbbh: contactDialogDbbh.value,
    xm: row.xm,
    sj: row.sj,
    wxh: row.wxh,
    zw: row.zw,
    qx: row.qx,
    sfjf: row.sfjf,
    yhID: row.yhID,
  });
  contactEditDialogVisible.value = true;
  nextTick(() => {
    contactTab.value = "contact";
  });
}

// 提交联系人表单
function submitContactForm() {
  contactFormRef.value.validate((valid) => {
    if (!valid) return;

    if (contactEditMode.value) {
      // 编辑
      updateContact({ ...contactForm, yhID: contactForm.yhID }).then(() => {
        proxy.$modal.msgSuccess("联系人更新成功");
        contactEditDialogVisible.value = false;
        fetchContactList();
      });
    } else {
      // 新增
      addContact({ ...contactForm }).then(() => {
        proxy.$modal.msgSuccess("联系人新增成功");
        contactEditDialogVisible.value = false;
        fetchContactList();
      });
    }
  });
}

/** 查询电表列表 */
function getList() {
  loading.value = true;
  const api = activeTab.value === "used" ? useList : freeList;
  api(queryParams.value).then((response) => {
    if (response.code !== 200) {
      loading.value = false;
      return;
    }
    tableData.value = response.data?.list;
    total.value = response.data?.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    dbbh: undefined,
    zt: undefined,
    lc: undefined,
  };
  getList();
}

/** Tab 切换 */
function handleTabChange(tab, event) {
  console.log(tab, event);
  activeTab.value = tab.props.name;
  queryParams.value.pageNum = 1;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  resetForm();
  open.value = true;
  title.value = "新增电表";
  fetchCarrierList();
  fetchPurposeList();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  resetForm();
  form.value = { ...row };
  open.value = true;
  title.value = "修改电表";
  fetchCarrierList();
  fetchPurposeList();
}

// /** 删除按钮操作 */
// function handleDelete(row) {
//   deleteMeter(row.dbbh).then(() => {
//     getList();
//   });
// }

/** 提交表单 */
function submitForm() {
  // 新增和编辑都校验
  proxy.$refs.meterRef.validate((valid) => {
    if (!valid) return;
    if (form.value.dbbh) {
      // updateMeter(form).then(() => {
      //   open.value = false;
      //   getList();
      // });
    } else {
      addMeter(form.value).then(() => {
        open.value = false;
        proxy.$modal.msgSuccess("电表新增成功");
        getList();
      });
    }
  });
}

/** 获取载体列表 */
function fetchCarrierList() {
  selectzt({ lxbh: 1, pageNum: 1, pageSize: 10 }).then((response) => {
    carrierList.value = response.data.list || [];
  });
}

/** 获取电表用途列表 */
function fetchPurposeList() {
  selectzt({ lxbh: 2, pageNum: 1, pageSize: 10 }).then((response) => {
    purposeList.value = response.data || [];
  });
}

/** 载体选择时获取 nr 和 nra 并赋值 */
function handleCarrierChange(value) {
  const selectedCarrier = carrierList.value.find((item) => item.nr === value);
  if (selectedCarrier) {
    form.value.nr = selectedCarrier.nr; // 赋值 nr
    form.value.nra = selectedCarrier.nra; // 赋值 nra
    fetchZlList();
  }
}

/** 重置表单 */
function resetForm() {
  form.value = {
    dbbh: undefined,
    nr: undefined,
    nra: undefined,
    lc: undefined,
    location: undefined,
    magnification: undefined,
    tid: undefined,
    zlid: undefined,
  };
}
// 表单取消
function cancel() {
  resetForm();
  open.value = false;
}

/** 启用关联按钮操作 */
function handleEnableAssociation(row) {
  enableForm.dbbh = row.dbbh; // 设置电表编号
  enableForm.csdl = row.csdl; // 设置初始电量

  // 获取企业列表
  enterpriseList({ zt: row.zt }).then((response) => {
    enterpriseListData.value = response.data || [];
  });

  // 获取房源列表
  selectRoom({ zt: row.zt, lc: row.lc }).then((response) => {
    roomListData.value = response.data || [];
  });

  // 获取电表用途列表
  fetchPurposeList();

  enableDialogVisible.value = true; // 打开对话框
}

/** 启用日期选择时调用接口获取初始电量 */
function handleEnableDateChange(date) {
  if (!date || !enableForm.dbbh) return;

  startDayPower({ dbbh: enableForm.dbbh, qysj: date }).then((response) => {
    if (response.code === 200 && response.data.length > 0) {
      enableForm.csdl = response.data[0].dbz; // 将返回的电表值赋值给初始电量
    } else {
      enableForm.csdl = 0; // 如果接口未返回数据，设置为默认值
    }
  });
}

/** 电表用途选择时动态调整企业名称输入方式 */
function handlePurposeChange(value) {
  if (value === "自用" || value === "公用") {
    enableForm.qymc = ""; // 清空企业名称
    enableForm.khbh = null; // 设置客户编号为 null
  } else if (value === "租用") {
    enableForm.qymc = ""; // 清空企业名称
    enableForm.khbh = ""; // 清空客户编号
  }
}

/** 企业名称选择时赋值客户编号 */
function handleEnterpriseChange(value) {
  const selectedEnterprise = enterpriseListData.value.find((item) => item.qymc === value);
  if (selectedEnterprise) {
    enableForm.khbh = selectedEnterprise.khbh; // 赋值客户编号
  }
}

// 提交启用关联
function submitEnableAssociation() {
  enableFormRef.value.validate((valid) => {
    if (!valid) return;
    let fjhValue = "";
    // 公用时不传房间号
    if (enableForm.yt !== "公用") {
      fjhValue = Array.isArray(enableForm.fjh)
        ? enableForm.fjh.join(",")
        : enableForm.fjh;
    }
    startAssociation({
      dbbh: enableForm.dbbh,
      qymc: enableForm.qymc,
      fjh: fjhValue,
      yt: enableForm.yt,
      qysj: enableForm.qysj,
      csdl: enableForm.csdl,
      khbh: enableForm.khbh,
    }).then(() => {
      enableDialogVisible.value = false; // 关闭对话框
      resetEnableForm(); // 初始化表单
      getList(); // 刷新列表
    });
  });
}

/** 初始化启用关联表单 */
function resetEnableForm() {
  enableForm.dbbh = ""; // 电表编号
  enableForm.qymc = ""; // 企业名称
  enableForm.fjh = []; // 房源编号
  enableForm.yt = "租用"; // 电表用途
  enableForm.qysj = ""; // 启用日期
  enableForm.csdl = 0; // 初始电量
  enableForm.khbh = null; // 客户编号
}

/** 取消启用关联 */
function cancelEnableAssociation() {
  enableDialogVisible.value = false;
}

/** 退用取消关联按钮操作 */
function handleWithdraw(row) {
  withdrawRow = row;
  withdrawForm.dbbh = row.dbbh;
  withdrawForm.qymc = row.qymc;
  withdrawForm.fjh = row.fjh;
  withdrawForm.dbyt = row.dbyt;
  withdrawForm.tysj = parseTime(new Date(), "{y}-{m}-{d}");
  withdrawForm.zzdl = "";
  withdrawDialogVisible.value = true;
  // 自动获取今天的最终电量
  handleWithdrawDateChange(withdrawForm.tysj);
}

function handleWithdrawDateChange(date) {
  if (!date || !withdrawForm.dbbh) return;
  startDayPower({ dbbh: withdrawForm.dbbh, qysj: date }).then((response) => {
    if (response.code === 200 && response.data.length > 0) {
      withdrawForm.zzdl = response.data[0].dbz;
    } else {
      withdrawForm.zzdl = "";
    }
  });
}

function submitWithdraw() {
  withdrawFormRef.value.validate((valid) => {
    if (!valid) return;
    withdraw({
      dbbh: withdrawForm.dbbh,
      tysj: withdrawForm.tysj,
      zzdl: withdrawForm.zzdl,
    }).then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("退用取消关联成功！");
        withdrawDialogVisible.value = false;
        getList();
      } else {
        proxy.$modal.msgError(res.msg || "退用取消关联失败！");
      }
    });
  });
}
// 载体或楼层变动时/下拉聚焦时调用
function fetchZlList() {
  if (!form.value.nr || !form.value.lc) {
    zlList.value = [];
    return;
  }
  selectAllZl({ zt: form.value.nr, lc: form.value.lc }).then((res) => {
    zlList.value = res.data || [];
  });
}

const updateRoomForm = reactive({
  dbid: "",
  zt: "",
  qymc: "",
  khbh: "",
  fjh: "",
});

// 点击“使用中”列表的关联房间时
function handleUpdateRoom(row) {
  // 获取上半区信息
  selectAmmeter1({
    qymc: row.qymc,
    khbh: row.khbh,
    dbid: row.dbid,
  }).then((res) => {
    if (res.code === 200 && res.data) {
      Object.assign(updateRoomForm, {
        dbid: res.data[0].dbid,
        zt: res.data[0].zt,
        qymc: res.data[0].qymc,
        khbh: res.data[0].khbh,
        fjh: res.data[0].fjh,
      });
      // 先获取房间列表，再自动勾选
      selectRoom1({
        qymc: row.qymc,
        khbh: row.khbh,
        dbid: row.dbid,
      }).then((roomRes) => {
        roomList.value = roomRes.data || [];
        // 自动勾选：fjh可能为逗号分隔字符串
        const fjhArr = (updateRoomForm.fjh || "")
          .split(",")
          .map((f) => f.trim())
          .filter((f) => f);

        // 先清空所有勾选
        selectedRooms.value = [];
        nextTick(() => {
          if (proxy.$refs.roomTableRef) {
            proxy.$refs.roomTableRef.clearSelection();
            // 只勾选存在于房间列表的房间号
            roomList.value.forEach((item) => {
              if (fjhArr.includes(item.fjh)) {
                proxy.$refs.roomTableRef.toggleRowSelection(item, true);
                selectedRooms.value.push(item.fjh);
              }
            });
          }
        });
      });
      updateRoomDialogVisible.value = true;
    }
  });
}

// 房间勾选变化
function handleRoomSelectionChange(selection) {
  selectedRooms.value = selection.map((item) => item.fjh);
}

// 提交更新房间
function submitUpdateRoom() {
  if (!selectedRooms.value.length) {
    proxy.$modal.msgWarning("请选择要关联的房间");
    return;
  }
  // 对房间号去重
  const uniqueFjh = Array.from(new Set(selectedRooms.value)).join(",");
  updateRoom({
    dbid: updateRoomForm.dbid,
    fjh: uniqueFjh,
    qymc: updateRoomForm.qymc,
    khbh: updateRoomForm.khbh,
  }).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("关联房间更新成功！");
      updateRoomDialogVisible.value = false;
      getList();
    } else {
      proxy.$modal.msgError(res.msg || "更新失败");
    }
  });
}
const invoiceInfo = ref(null);
const invoiceEditDialogVisible = ref(false);
const invoiceForm = reactive({
  qymc: "",
  khbh: "",
  yyzzh: "",
  zt: "",
  jflx: "",
  hkzje: 0,
  yszje: 0,
  wszje: 0,
  kpqym: "",
  kpsh: "",
  kplx: "",
  Kkpje: 0,
  ykpje: 0,
  wkpje: 0,
  qyzt: "",
});
const invoiceFormRef = ref();

function openAddContactDialog() {
  contactEditMode.value = false;
  const isFirst = !contactList.value || contactList.value.length === 0;
  Object.assign(contactForm, {
    qymc: contactDialogQymc.value,
    khbh: contactDialogKhbh.value,
    dbbh: contactDialogDbbh.value,
    xm: "",
    sj: "",
    wxh: "",
    zw: "",
    qx: isFirst ? 6 : "",
    sfjf: 0,
    yhID: undefined,
  });
  contactEditDialogVisible.value = true;
  nextTick(() => {
    contactTab.value = "contact";
  });
}
function fetchInvoiceInfo() {
  invoiceInfo.value = null;
  if (!contactDialogKhbh.value) return;
  selectzh({ khbh: contactDialogKhbh.value })
    .then((res) => {
      if (res.code === 200 && res.data) {
        invoiceInfo.value = res.data;
      } else {
        invoiceInfo.value = null;
      }
    })
    .catch(() => {
      invoiceInfo.value = null;
    });
}
function openInvoiceEditDialog() {
  // 编辑时带入已有数据
  if (invoiceInfo.value) {
    Object.assign(invoiceForm, invoiceInfo.value);
  } else {
    Object.assign(invoiceForm, {
      qymc: contactDialogQymc.value,
      khbh: contactDialogKhbh.value,
      yyzzh: "",
      zt: "",
      jflx: "",
      hkzje: 0,
      yszje: 0,
      wszje: 0,
      kpqym: "",
      kpsh: "",
      kplx: "",
      Kkpje: 0,
      ykpje: 0,
      wkpje: 0,
      qyzt: "",
    });
  }
  invoiceEditDialogVisible.value = true;
}
function submitInvoiceForm() {
  invoiceFormRef.value.validate?.((valid) => {
    if (valid === false) return;
    addInvoice({ ...invoiceForm }).then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("补充开票信息成功");
        invoiceEditDialogVisible.value = false;
        fetchInvoiceInfo();
      } else {
        proxy.$modal.msgError(res.msg || "补充失败");
      }
    });
  });
}

getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
